import 'dart:convert';

import 'package:encrypt_and_decrypt_files/dio_util.dart';
import 'package:encrypt_and_decrypt_files/home_page.dart';
import 'package:encrypt_and_decrypt_files/my/login_page.dart';
import 'package:encrypt_and_decrypt_files/my/register_page.dart';
import 'package:encrypt_and_decrypt_files/widget/extension.dart';
import 'package:encrypt_and_decrypt_files/widget/local_language_provider.dart';
import 'package:encrypt_and_decrypt_files/widget/theme_provider.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await SpUtil.getInstance();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    if (SpUtil.getString('token') != null &&
        SpUtil.getString('token')!.isNotEmpty) {
      UserModel userModel = SpUtil.getObj('userModel', (map) {
        return UserModel.fromJson(map as Map<String, dynamic>);
      })!;
      login(userModel.email!, userModel.password!);
    }
    super.initState();
  }

  Future<void> login(String email, String password) async {
    const url = '/login';

    var params = {
      'email': email,
      'password': password,
    };
    var response = await DioHttp.of(context).post(url, params, '');

    var resString = json.decode(response.toString());
    if (resString['code'] == 200) {
      SpUtil.putString('token', resString['data']['access_token'] ?? '');
      SpUtil.putObject(
          'userModel',
          UserModel(
            email: email,
            password: password,
            userId: resString['data']['user_id'],
            memberType: resString['data']['memberType'],
          ));
    }
    // Toast.show(resString['msg']);
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => LanguageProvider()),
        ChangeNotifierProvider(create: (_) => ThemeProvider()),
      ],
      child: MaterialApp(
        title: 'Encrypt',
        home: SpUtil.getString('token') != null &&
                SpUtil.getString('token')!.isNotEmpty
            ? const HomePage()
            : const LoginPage(),
      ),
    );
  }
}
